package replaceWords;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ReplaceWord {

	final String tagStringForWords = "XX";
	final long errorSleep = 2000;

	String replaceWord(String wordSource) throws Exception {
		String wordReplace = wordSource;
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;

		Class.forName("com.mysql.jdbc.Driver");
		conn = DriverManager.getConnection("jdbc:mysql://" + wordHost + "/" + wordDBName + "?user=root");
		stmt = conn.createStatement();
		rs = stmt.executeQuery("select * from words where sort >9000");
		while (rs.next()) {
			String word = rs.getString("word");
			String ids = tagStringForWords + rs.getInt("id") + tagStringForWords;
			Pattern p = Pattern.compile(word);
			Matcher m = p.matcher(wordReplace);
			wordReplace = m.replaceAll(ids);
		}

		try {
			if (rs != null) {
				rs.close();
				rs = null;
			}
			if (stmt != null) {
				stmt.close();
				stmt = null;
			}
			if (conn != null) {
				conn.close();
				conn = null;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}

		// 正常的运行替换完成了，break跳出死循环

		return (wordReplace);

	}

	String replaceNum(String wordSource) throws Exception {
		String NumReplace = wordSource;
		Connection conn = null;
		Statement stmt = null;
		ResultSet rs = null;
		Class.forName("com.mysql.jdbc.Driver");
		conn = DriverManager.getConnection("jdbc:mysql://" + wordHost + "/" + wordDBName + "?user=root");
		stmt = conn.createStatement();
		rs = stmt.executeQuery("select * from words where sort >9000");
		while (rs.next()) {
			String word = rs.getString("newone");
			String ids = tagStringForWords + rs.getInt("id") + tagStringForWords;
			Pattern p = Pattern.compile(ids);
			Matcher m = p.matcher(NumReplace);
			NumReplace = m.replaceAll(word);
		}

		return (NumReplace);
	}

	String wordHost = null;
	String wordDBName = null;

	public void setWordHost(String wordHost) {
		this.wordHost = wordHost;
	}

	public void setWordDBName(String wordDBName) {
		this.wordDBName = wordDBName;
	}

}
